package com.eqdd.yiqidian.ui.mine.space.fragment

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import cn.bingoogolapple.bgabanner.BGABanner
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.BGABannerAdapter
import com.eqdd.yiqidian.adapter.recycleadapter.BaseMultiItemQuickAdapter
import com.eqdd.yiqidian.adapter.recycleadapter.BaseViewHolder
import com.eqdd.yiqidian.adapter.recycleadapter.entity.MultiItemEntity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.CompanyDetailBean
import com.eqdd.yiqidian.bean.TeamMemberBean
import com.eqdd.yiqidian.box.ItemDecoration.ITitleItemInterface
import com.eqdd.yiqidian.box.ItemDecoration.TitleItemDecoration
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonCallBack
import com.eqdd.yiqidian.kotlin.imgPathPreview
import com.eqdd.yiqidian.kotlin.listImagePreview
import com.eqdd.yiqidian.ui.companyspace.*
import com.eqdd.yiqidian.utils.ImageUtil
import com.gamerole.richtextview.RichEditor
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_company_space_detail.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.support.v4.startActivity
import org.jetbrains.anko.support.v4.toast
import java.util.*


/**
 * Created by jhj on 18-7-4.
 */
class InfoFragment : Fragment() {

    private var linearLayoutManager: LinearLayoutManager? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_company_space_detail, container, false)
        linearLayoutManager = LinearLayoutManager(activity)
        initData(view)
        return view
    }

    private fun initData(view: View) {
        val userGuid = arguments?.getString(Config.GUID)
        val userCompanyId = arguments?.getInt("userCompanyId")
        val companyId = arguments?.getInt(Config.COMPANY_ID)

        if (userGuid == null || companyId == null || userCompanyId == null) {
            return
        }

        OkGo.post<HttpResult<CompanyDetailBean>>(HttpConfig.BASE_URL + HttpConfig.COMPANY_SPACE_DETAIL)
                .params("userGuid", userGuid)
                .params("userGompanyId", userCompanyId)
                .params("companyId", companyId)
                .execute(object : JsonCallBack<HttpResult<CompanyDetailBean>>() {
                    override fun onSuccess(response: Response<HttpResult<CompanyDetailBean>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            val bean = result.items
                            formatData(bean, view)

                        } else {
                            toast(result?.msg ?: "获取信息失败")
                            activity?.finish()
                            return
                        }
                    }

                })


    }


    private fun formatData(items: CompanyDetailBean, view: View) {

        Observable
                .create<List<ItemBean>> {
                    val list = arrayListOf<ItemBean>()

                    items.let {
                        val bean = ItemBean()
                        bean.isTitle = true
                        bean.comImg = it.comImage.map { it.imgUrl }
                        bean.comDesc = it.comDesc
                        bean.type = 0
                        list.add(bean)
                    }
                    items.comOrganization?.forEach {
                        val bean = ItemBean()
                        bean.id = it.id
                        bean.image = it.imageUrl
                        bean.describe = it.describe
                        bean.sort = it.sort
                        bean.tag = "组织机构"
                        bean.type = 1
                        list.add(bean)
                    }
                    list.add(moreData(5, "组织机构", items.companyId))
                    items.comEquipment?.forEach {
                        val bean = ItemBean()
                        bean.id = it.id
                        bean.image = it.image
                        bean.equipmentName = it.equipmentName
                        bean.manufactor = it.manufactor
                        bean.date = it.dateOfPurchase
                        bean.tag = "设备展示"
                        bean.type = 2
                        list.add(bean)
                    }
                    list.add(moreData(5, "设备展示", items.companyId))
                    items.comTeam?.forEach {
                        val bean = ItemBean()
                        bean.id = it.id
                        bean.image = it.headImage
                        bean.name = it.userName
                        bean.post = it.post
                        bean.msg = it.msg
                        bean.type = 3
                        bean.tag = "团队成员"
                        list.add(bean)
                    }
                    list.add(moreData(5, "团队成员", items.companyId))
                    items.comCotact?.let {
                        val bean = ItemBean()
                        bean.contacts = it.contacts
                        bean.contactNumber = it.contactNumber
                        bean.seatMachine = it.seatMachine
                        bean.fax = it.fax
                        bean.email = it.email
                        bean.address = it.address
                        bean.type = 4
                        bean.tag = "团队成员"
                        bean.companyId = it.companyId
                        list.add(bean)
                    }

                    it.onNext(list)
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    val density: Float = activity?.resources?.displayMetrics?.density ?: 3f

                    val itemDecoration = TitleItemDecoration(activity, TitleItemDecoration.DECORATION_FOLD_TYPE)
                    itemDecoration
                            .setmTitleHeight(((45 * density).toInt()))
                            .setColorTitleBg(0xfff1f1f1.toInt())
                            .setColorTitleLine(0xff777777.toInt())
                            .setDatas(it)

                    view.recyclerView.layoutManager = linearLayoutManager
                    view.recyclerView.addItemDecoration(itemDecoration)
                    val adapter = ItemAdapter(it)
                    view.recyclerView.adapter = adapter

                }
    }

    private fun moreData(type: Int, tag: String, companyId: Int): ItemBean {
        val itemBean = ItemBean()
        itemBean.type = type
        itemBean.tag = tag
        itemBean.companyId = companyId
        return itemBean
    }


    inner class ItemAdapter(val dataList: List<ItemBean>) : BaseMultiItemQuickAdapter<ItemBean, BaseViewHolder>(dataList) {

        init {
            addItemType(0, R.layout.list_item_158)
            addItemType(1, R.layout.list_item_160)
            addItemType(2, R.layout.list_item_153)
            addItemType(3, R.layout.list_item_153)
            addItemType(4, R.layout.list_item_159)
            addItemType(5, R.layout.list_item_165)
        }

        override fun convert(helper: BaseViewHolder?, item: ItemBean?) {
            when (helper?.itemViewType) {
                0 -> {
                    val banner = helper.getView<BGABanner>(R.id.banner_viewpager)
                    val richEditor = helper.getView<RichEditor>(R.id.richEditor)
                    banner.setAdapter(BGABannerAdapter(activity))
                    banner.setData(item?.comImg, null)
                    richEditor.setInputEnabled(false)
                    richEditor.setPadding(10, 0, 10, 0)
                    val html = item?.comDesc
                            ?.replace("<pre>", "")
                            ?.replace("</pre>", "")
                            ?.replace("<br>", "")
                    richEditor.html = html
                }
                1 -> {
                    val imageView = helper.getView<ImageView>(R.id.iv_image)
                    if (item?.image.isNullOrBlank()) {
                        imageView.visibility = View.GONE
                    } else {
                        imageView.visibility = View.VISIBLE
                        item?.image?.let { activity?.listImagePreview(it, imageView) }
                    }
                    helper.setText(R.id.tv_content, item?.describe)
                }
                2 -> {
                    val imageView = helper.getView<ImageView>(R.id.iv_image)
                    if (item?.image.isNullOrBlank()) {
                        imageView.visibility = View.GONE
                    } else {
                        imageView.visibility = View.VISIBLE
                        imageView.onClick {
                            item?.image?.let { activity?.imgPathPreview(it) }
                        }
                        Glide.with(activity)
                                .asBitmap()
                                .apply(ImageUtil.optionsNormal)
                                .load(item?.image)
                                .into(object : SimpleTarget<Bitmap>() {
                                    override fun onResourceReady(resource: Bitmap?, transition: Transition<in Bitmap>?) {
                                        if (resource == null) return
                                        val scale = resource.width.toDouble() / resource.height.toDouble()
                                        if (scale < 0.85 && scale > 0.65) {
                                            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                                            imageView.setImageBitmap(resource)
                                        } else {
                                            imageView.setImageBitmap(resource)
                                        }
                                    }

                                })

                    }
                    helper.setText(R.id.tv_name, String.format(Locale.CHINA, "设备名称：%s", item?.equipmentName))
                    helper.setText(R.id.tv_post, String.format(Locale.CHINA, "生产厂商：%s", item?.manufactor))
                    helper.setText(R.id.tv_msg, String.format(Locale.CHINA, "购买日期：%s", item?.date))
                }
                3 -> {
                    val imageView = helper.getView<ImageView>(R.id.iv_image)
                    if (item?.image.isNullOrBlank()) {
                        imageView.visibility = View.GONE
                    } else {
                        imageView.visibility = View.VISIBLE
                        imageView.onClick {
                            item?.image?.let { activity?.imgPathPreview(it) }
                        }
                        Glide.with(activity)
                                .asBitmap()
                                .apply(ImageUtil.optionsNormal)
                                .load(item?.image)
                                .into(object : SimpleTarget<Bitmap>() {
                                    override fun onResourceReady(resource: Bitmap?, transition: Transition<in Bitmap>?) {
                                        if (resource == null) return
                                        val scale = resource.width.toDouble() / resource.height.toDouble()
                                        if (scale < 0.85 && scale > 0.65) {
                                            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                                            imageView.setImageBitmap(resource)
                                        } else {
                                            imageView.setImageBitmap(resource)
                                        }
                                    }

                                })

                    }
                    helper.setText(R.id.tv_name, String.format(Locale.CHINA, "姓名：%s", item?.name))
                    helper.setText(R.id.tv_post, String.format(Locale.CHINA, "职位：%s", item?.post))
                    helper.setText(R.id.tv_msg, String.format(Locale.CHINA, "简介：%s", item?.msg))
                }
                4 -> {
                    helper.setText(R.id.tv_contact, item?.contacts)
                    helper.setText(R.id.tv_phone, item?.contactNumber)
                    helper.setText(R.id.tv_telephone, item?.seatMachine)
                    helper.setText(R.id.tv_email, item?.email)
                    helper.setText(R.id.tv_position, item?.address)
                    helper.getView<TextView>(R.id.tv_phone).setOnClickListener {
                        val intent = Intent(Intent.ACTION_DIAL)
                        val url = Uri.parse("tel:" + (it as TextView).text.toString())
                        intent.data = url
                        mContext.startActivity(intent)
                    }
                    helper.getView<TextView>(R.id.tv_telephone).setOnClickListener {
                        val intent = Intent(Intent.ACTION_DIAL)
                        val url = Uri.parse("tel:" + (it as TextView).text.toString())
                        intent.data = url
                        mContext.startActivity(intent)
                    }
                }
                5 -> {
                    val textView = helper.getView<TextView>(R.id.tv_more)
                    textView.onClick {
                        if (item?.tag == "组织机构") {
                            startActivity<OrganizationListActivity>(Config.COMPANY_ID to item.companyId, Config.TYPE to 1)
                        } else if (item?.tag == "设备展示") {
                            startActivity<EquipmentListActivity>(Config.COMPANY_ID to item.companyId, Config.TYPE to 1)
                        } else if (item?.tag == "团队成员") {
                            startActivity<TeamMemberListActivity>(Config.COMPANY_ID to item.companyId, Config.TYPE to 1)
                        }
                    }

                }

            }
            helper?.itemView?.onClick {
                if (item?.type == 2) {
                    startActivity<EquipmentInfoActivity>(Config.TYPE to 1, Config.ID to item.id)
                } else if (item?.type == 3) {
                    val teamMember = TeamMemberBean()
                    teamMember.headImage = item.image
                    teamMember.id = item.id
                    teamMember.userName = item.name
                    teamMember.post = item.post
                    teamMember.msg = item.msg
                    startActivity<TeamMemberInfoActivity>(Config.TYPE to 1, "data" to teamMember)
                }
            }
        }

    }


    class ItemBean : ITitleItemInterface, MultiItemEntity {

        var id: Int = -1
        var image: String? = null
        var tag: String = ""
        var type: Int = -1
        var isTitle: Boolean = false

        //组织机构
        var describe: String? = null
        var sort: Int? = null

        //设备信息
        var equipmentName: String? = null
        var manufactor: String? = null
        var date: String? = null

        //成员
        var name: String? = null
        var post: String? = null
        var msg: String? = null

        //空间
        var comImg: List<String>? = null
        var comDesc: String? = null

        //个人信息
        var contacts: String? = null // 闫浩杰
        var contactNumber: String? = null//15690783806
        var seatMachine: String? = null//0371123
        var fax: String? = null//123456789
        var email: String? = null//15286837836@qq.com
        var address: String? = null//山西省大同市新荣区fg
        var companyId: Int = 0


        override fun isShowTitle(): Boolean {
            return !isTitle
        }

        override fun getAlphaTag(): String {
            return tag
        }

        override fun getItemType(): Int {
            return type
        }
    }
}